package log

import (
	"io"
	"os"
	es "qabx.net/common/es"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	log "github.com/sirupsen/logrus"
	"gopkg.in/sohlich/elogrus.v7"
)

var logEs *log.Logger

func InitLogFile(linkName string, logLevel log.Level, path ...string) error {
	//设置日志文件及日志分割，保留24小时日志，1个小时分割一个文件。
	var logPath = "./logs/"
	if len(path) > 0 {
		logPath = path[0]
	}
	logf, err := rotatelogs.New(
		logPath+linkName+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(logPath+linkName+".log"),
		rotatelogs.WithMaxAge(65535*time.Hour),
		rotatelogs.WithRotationTime(time.Hour),
	)
	if err != nil {
		log.Error("get log file failed")
		return err
	}
	mv := io.MultiWriter(os.Stdout, logf)
	log.SetOutput(mv)
	log.SetLevel(logLevel)
	log.SetFormatter(&log.TextFormatter{
		DisableColors: true,
		FullTimestamp: true,
	})

	return nil
}

func InitEsLog(linkName string, listenStr string) {
	logEs = log.New()                        //创建logrus对象
	logEs.SetFormatter(&log.JSONFormatter{}) //设置logrus的日志格式为json

	//#将logrus和elastic绑定，localhost 是指定该程序执行时的ip
	hook, err := elogrus.NewElasticHook(es.ESClient, listenStr, logEs.Level, linkName)
	if err != nil {
		log.Panic(err)
	}
	log.AddHook(hook)
}
